﻿using Microsoft.Phone.Controls;
using Chicken4wp.Services;
using System.Windows.Navigation;
using Chicken4wp.Entities;
using System.Linq;

namespace Chicken4wp.ViewModels
{
    public class ProxySettingFinishPageViewModel
    {
        private readonly StorageService storageService;
        private WebBrowser browser;

        public ProxySettingFinishPageViewModel(StorageService storageService)
        {
            this.storageService = storageService;
        }

        public void Browser_Loaded(WebBrowser browser)
        {
            this.browser = browser;
            browser.ScriptNotify += browser_ScriptNotify;
            browser.Navigated += browser_Navigated;
            browser.Navigate(storageService.GetUri("ProxySettingFinish"));
        }

        void browser_Navigated(object sender, NavigationEventArgs e)
        {
            var currentProxy = ChickenDataContext.Instance.Settings.FirstOrDefault
                (s => s.Type == SettingType.ProxySetting && s.IsEnabled && s.IsInUsed);
            var browser = sender as WebBrowser;
            browser.InvokeScript("onload", "www/plugins/proxies/" + currentProxy.Path + ".js");
            browser.InvokeScript("initialize");
        }

        public void AppBar_Finish()
        {
            browser.InvokeScript("submit");
        }

        void browser_ScriptNotify(object sender, NotifyEventArgs e)
        {
            var browser = sender as WebBrowser;
            var currentProxy = ChickenDataContext.Instance.Settings.FirstOrDefault
                (s => s.Type == SettingType.ProxySetting && s.IsEnabled && s.IsInUsed);
            currentProxy.Data = e.Value;
            ChickenDataContext.Instance.SubmitChanges();
        }
    }
}
